import OperationCol from '@/components/OperationCol'
import SealStatus, { statusList } from '@/components/SealStatus'
import payOrder from '@/lib/request/payOrder'
import { payTypes } from '@/lib/sealFormat'
// import {Base64} from "js-base64";
import {
  formatStatus,
  orderStatusList,
  statusColor,
  expressPayTypes,
} from '@/lib/sealFormat'
import { desensitization, formatTime } from '@/lib/utils'
import { RootState } from '@/store'
import { Component, Vue } from 'vue-property-decorator'
import { Action, Mutation, State } from 'vuex-class'
import styles from '../NewApply/NewApply.less'
import style from './MyOrderList.less'
import { Table } from 'element-ui'
import operationStyles from '@/components/OperationCol.less'
import ApplyInvoice from '@/views/NewApply/ApplyInvoice'
import RefundDialog from '@/views/NewApply/refundDialog'
import ApplyInvoiceDialog from '@/components/applyInvoiceDialog/ApplyInvoiceDialog'
import TableEmpty from '@/components/tableEmpty'

// const statusList: any[] = [
// 	{
// 		id: 0,
// 		value: "全部"
// 	},
// 	{
// 		id: 1,
// 		value: "新增"
// 	},
// 	{
// 		id: 2,
// 		value: "待审核"
// 	}
// ];

const amountList: any[] = [
  { label: '电子印章服务费（含证书）', key: 1 },
  { label: '硬件介质费用', key: 2 },
  { label: '加密机硬件费', key: 3 },
  { label: '快递费', key: 4 },
]

const typeList: any = {
  all: [0],
  waitPay: [1, 5, 6],
  waitSend: [2],
  waitReceive: [3],
  refund: [90, 91, 92, 93, 94, 95],
}

const orderStatusColor = [
  {
    id: 1,
    color: '#1890FF',
    text: '待付款',
  },
  {
    id: 2,
    color: '#1890FF',
    text: '待发货',
  },
  {
    id: 3,
    color: '#1890FF',
    text: '待收货',
  },
  {
    id: 4,
    color: '#52C41A',
    text: '交易完成',
  },
  {
    id: 5,
    color: '#1890FF',
    text: '待付款',
  },
  {
    id: 6,
    color: '#1890FF',
    text: '待付款',
  },
  {
    id: 90,
    color: '#1890FF',
    text: '退款待处理',
  },
  {
    id: 91,
    color: '#1890FF',
    text: '退款待处理',
  },
  {
    id: 92,
    color: '#1890FF',
    text: '退款待处理',
  },
  {
    id: 93,
    color: '#1890FF',
    text: '退款待处理',
  },
  {
    id: 94,
    color: '#52C41A',
    text: '退款成功',
  },
  {
    id: 95,
    color: '#1890FF',
    text: '退款待处理',
  },
  {
    id: 96,
    color: '#F5222D',
    text: '订单关闭',
  },
  {
    id: 97,
    color: '#F5222D',
    text: '订单关闭',
  },
  {
    id: 98,
    color: '#F5222D',
    text: '订单关闭',
  },
  {
    id: 99,
    color: '#F5222D',
    text: '订单关闭',
  },
]

@Component({})
export default class MyOrderList extends Vue {
  applyInvoiceDialogVisible: boolean = false
  applyInvoicePayOrderId: number | undefined
  type: string = 'all'
  daterange = ''
  createStartTime?: string
  createEndTime?: string
  orderNo: any = ''
  applyOrganizeName: string = ''
  payer: string = ''
  payType: any = ''
  payStatus: any[] = []
  loading = false
  orderList: any[] = []
  pageIndex = 1
  pageSize = 10
  total = 0
  timer = 0
  orderCloseTimer = 0
  invoiceDisabled: any = false
  pickerOptions = {
    shortcuts: [
      {
        text: '最近一周',
        onClick(picker: any) {
          const end = new Date()
          const start = new Date()
          start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
          picker.$emit('pick', [start, end])
        },
      },
      {
        text: '最近一个月',
        onClick(picker: any) {
          const end = new Date()
          const start = new Date()
          start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
          picker.$emit('pick', [start, end])
        },
      },
      {
        text: '最近三个月',
        onClick(picker: any) {
          const end = new Date()
          const start = new Date()
          start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
          picker.$emit('pick', [start, end])
        },
      },
    ],
  }
  refundList: any[] = [
    {
      id: 'refunding',
      key: 90,
      name: '退款待处理',
    },
    {
      id: 'refundSuccess',
      key: 94,
      name: '退款成功',
    },
  ]
  typeList: any[] = [
    {
      id: 'all',
      key: 0,
      tag: 'allStatusCount',
      name: '所有订单',
      total: 0,
    },
    {
      id: 'waitPay',
      key: 1,
      tag: 'waitPayCount',
      name: '待付款',
      total: 0,
    },
    {
      id: 'waitSend',
      key: 2,
      tag: 'payFinishCount',
      name: '待发货',
      total: 0,
    },
    {
      id: 'waitReceive',
      key: 3,
      tag: 'shippedCount',
      name: '待收货',
      total: 0,
    },
    {
      id: 'over',
      key: 4,
      tag: 'shippedCount',
      name: '交易完成',
      total: 0,
    },
    {
      id: 'refund',
      key: 6,
      tag: 'refundCount',
      name: '退款管理',
      total: 0,
    },
    {
      id: 'close',
      key: 99,
      tag: 'shippedCount',
      name: '订单关闭',
      total: 0,
    },
  ]

  @State((state: RootState) => state.newApply.applyInvoiceVisible)
  applyInvoiceVisible!: boolean
  @State((state: RootState) => state.newApply.applyInvoiceData)
  applyInvoiceData!: any
  @State((state: RootState) => state.newApply.refundDialogVisible)
  refundDialogVisible!: boolean
  @State((state: RootState) => state.newApply.refundData)
  refundData!: any
  @Mutation('newApply/setStateData') setStateData!: (data: any) => {}

  @Action('newApply/receiptConfirm') receiptConfirm!: any
  @Action('paymentOrder/queryByOrderId') queryByOrderId!: any
  @Action('paymentOrder/queryPayOrderList') queryPayOrderList!: any
  @Action('paymentOrder/queryAllStatusCount') queryAllStatusCount!: any
  @Action('paymentOrder/cancelPayOrder') cancelPayOrder!: any
  @Action('paymentOrder/invoiceDownLoad') invoiceDownLoad!: any
  @Action('paymentOrder/invoiceDirect') invoiceDirect!: any

  protected render() {
    return (
      <div class={style.flex}>
        <div class={style.tabs}>
          {this.getTypeList.map((type: any) => {
            return (
              <p
                class={{
                  [style.tabPane]: true,
                  [style.active]: type.id === this.type,
                }}
                onClick={() => {
                  this.typeChange(type.id, type.key)
                }}
              >
                {type.name}
                {type.total !== 0 && <span>（{type.total}）</span>}
              </p>
            )
          })}
        </div>
        <div class={style.orderList}>
          <div class={style.content}>
            <div class={{ [styles.query]: true, custom: true }}>
              {this.type === 'all' && (
                <span class={[styles.part, style.formItem]}>
                  <span>交易状态</span>
                  <el-select
                    v-model={this.payStatus}
                    multiple
                    collapse-tags
                    placeholder="默认全部"
                  >
                    {this.typeList
                      .filter(type => type.key !== 0 && type.key !== 6)
                      .concat(this.refundList)
                      .map((sealType: any, index: number) => (
                        <el-option
                          key={sealType.key}
                          label={sealType.name}
                          value={sealType.key}
                        />
                      ))}
                  </el-select>
                </span>
              )}
              {this.type === 'refund' && (
                <span class={[styles.part, style.formItem]}>
                  <span>交易状态</span>
                  <el-select
                    v-model={this.payStatus}
                    multiple
                    collapse-tags
                    placeholder="默认全部"
                  >
                    {this.refundList.map((sealType: any, index: number) => (
                      <el-option
                        key={sealType.key}
                        label={sealType.name}
                        value={sealType.key}
                      />
                    ))}
                  </el-select>
                </span>
              )}
              <span class={[styles.part, style.formItem]}>
                <span>下单时间</span>
                <el-date-picker
                  size="mini"
                  v-model={this.daterange}
                  type="datetimerange"
                  prefix-icon="el-icon-date"
                  // picker-options={this.pickerOptions}
                  range-separator="至"
                  default-time={['00:00:00', '23:59:59']}
                  start-placeholder=""
                  end-placeholder=""
                />
              </span>
              <span class={[styles.part, style.formItem]}>
                <span>订单编号</span>
                <el-input
                  v-model={this.orderNo}
                  placeholder="请输入完整的订单编号"
                />
              </span>
              <span class={[styles.part, style.formItem]}>
                <span>用章机构名称</span>
                <el-input
                  v-model={this.applyOrganizeName}
                  placeholder="用章机构名称"
                />
              </span>
              <span class={[styles.part, style.formItem]}>
                <span>付费方</span>
                <el-input v-model={this.payer} placeholder="付费方" />
              </span>
              <span class={[styles.part, style.formItem]}>
                <span>付费方式</span>
                <el-select
                  v-model={this.payType}
                  placeholder="付费方式"
                  clearable
                >
                  {payTypes.map((item: any) => {
                    return <el-option label={item.value} value={item.id} />
                  })}
                </el-select>
              </span>
              <span class={[styles.part]}>
                <el-button
                  onClick={this.query}
                  loading={this.loading}
                  plain
                  class="min color-blue"
                >
                  搜索
                </el-button>
                <el-button onClick={this.reset} plain class="min color-gray">
                  重置
                </el-button>
              </span>
            </div>
            <el-table
              span-method={this.arraySpanMethod}
              data={this.orderList}
              class={this.orderList.length > 0 && 'notEmpty'}
              default-expand-all
              style="width: 100%"
              v-loading={this.loading}
              ref="table"
            >
              <TableEmpty
                v-show={!this.loading}
                slot="empty"
                msg="当前查询条件下暂无订单数据"
              >
                <el-button type="primary" onClick={this.toNewApply}>
                  前往申请印章
                </el-button>
              </TableEmpty>
              <el-table-column
                type="expand"
                width="1"
                {...{
                  scopedSlots: {
                    default: (scope: any) => {
                      return (
                        <div class={style.expand}>
                          <p class={style.goods}>
                            {scope.row.goods &&
                              scope.row.goods.map((goods: any) => {
                                return (
                                  <p
                                    class={style.goodContent}
                                    style={{
                                      height: `${(1 / scope.row.goods.length) *
                                        100}%`,
                                    }}
                                  >
                                    <p class={style.name}>{goods.name}</p>
                                    <p class={style.price}>
                                      {goods.price === '0.00' &&
                                        goods.goodsType === 2 && (
                                          <span class={style.invalid}>
                                            ￥35.00
                                          </span>
                                        )}
                                      ￥
                                      {(goods.price / goods.quantity).toFixed(
                                        2
                                      )}
                                    </p>
                                    <p class={style.total}>{goods.quantity}</p>
                                  </p>
                                )
                              })}
                          </p>
                          <p
                            class={{
                              [style.amount]: true,
                              'align-height': true,
                            }}
                          >
                            ￥{scope.row.payAmount}
                          </p>
                          <p
                            class={{
                              [style.amount]: true,
                              'align-height': true,
                            }}
                          >
                            {scope.row.applyOrganizeName}
                          </p>
                          <p
                            class={{
                              [style.amount]: true,
                              'align-height': true,
                            }}
                          >
                            {scope.row.payer}
                          </p>
                          <p
                            class={{
                              [style.amount]: true,
                              'align-height': true,
                            }}
                          >
                            {
                              payTypes.find(i => i.id === scope.row.payType)
                                ?.value
                            }
                          </p>
                          <p
                            class={{
                              [style.status]: true,
                              'align-height': true,
                            }}
                          >
                            <SealStatus
                              statusData={orderStatusColor.find(
                                item => scope.row.status === item.id
                              )}
                            />
                          </p>
                          <p
                            class={{ [style.opt]: true, 'align-height': true }}
                          >
                            <OperationCol
                              isBlock
                              operations={this.filterOpera(scope.row)}
                              showNum={14}
                              row={scope.row}
                              index={scope.$index}
                            />
                          </p>
                        </div>
                      )
                    },
                  },
                }}
              />
              <el-table-column
                prop="sealApplyRecordId"
                label="商品名称"
                width="344"
                show-overflow-tooltip
                {...{
                  scopedSlots: {
                    default: (scope: any) => {
                      return (
                        <p class="order-title">
                          <span class="order-no">
                            订单编号：{scope.row.orderNo}
                          </span>
                          &nbsp;
                          <span class="ml20">
                            申请编号：{scope.row.sealApplyRecordNo}
                          </span>
                          &nbsp;
                          <span class="ml20">
                            下单时间：{scope.row.createTime}
                          </span>
                          &nbsp;
                          {scope.row.orderCloseTime && scope.row.theTime ? (
                            <span class="ml20">
                              订单将于 {scope.row.closeTime} 后自动关闭
                            </span>
                          ) : (
                            ''
                          )}
                        </p>
                      )
                    },
                  },
                }}
              />
              <el-table-column
                prop="sealName"
                label="单价"
                width="138"
                show-overflow-tooltip
              />
              <el-table-column
                prop="organizeName"
                label="数量"
                width="113"
                show-overflow-tooltip
              />
              <el-table-column
                prop="crea2teTime"
                label="交易金额"
                width="158"
                show-overflow-tooltip
              />
              <el-table-column
                prop="applyOrganizeName"
                label="用章机构名称"
                width="158"
                show-overflow-tooltip
              />
              <el-table-column
                prop="payer"
                label="付费方"
                width="158"
                show-overflow-tooltip
              />
              <el-table-column
                prop="payType"
                label="付费方式"
                width="158"
                show-overflow-tooltip
              />
              <el-table-column
                prop="sealApplyStatuss"
                label="交易状态"
                width="149"
                show-overflow-tooltip
                // {...{
                //   scopedSlots: {
                //     default: (scope: any) => {
                //       return <SealStatus status={scope.row.sealApplyStatus} />;
                //     }
                //   }
                // }}
              />

              <el-table-column
                prop="id"
                label="交易操作"
                min-width="166"
                {...{
                  scopedSlots: {
                    default: (scope: any) => {
                      return ''
                    },
                  },
                }}
              />
            </el-table>
          </div>
        </div>
        {this.orderList && this.orderList.length > 0 && (
          <el-pagination
            class={{ [styles.pagination]: true, [style.pagination]: true }}
            onSize-change={this.handleSizeChange}
            onCurrent-change={this.handleCurrentChange}
            current-page={this.pageIndex}
            page-sizes={[10, 20, 30]}
            page-size={this.pageSize}
            layout="total, sizes, prev, pager, next, jumper"
            total={this.total}
            pager-count={5}
          />
        )}
        <ApplyInvoice
          visible={this.applyInvoiceVisible}
          defaultData={this.applyInvoiceData}
          onVisibleChange={(val: boolean) => {
            this.setStateData({ applyInvoiceVisible: val })
          }}
          onSubmitHandler={() => {
            this.query()
          }}
        />
        <RefundDialog
          visible={this.refundDialogVisible}
          defaultData={this.refundData}
          type="refundDetail"
          onVisibleChange={(val: boolean) => {
            this.setStateData({ refundDialogVisible: val })
          }}
        />
        <ApplyInvoiceDialog
          dialogVisible={this.applyInvoiceDialogVisible}
          payOrderId={this.applyInvoicePayOrderId}
          {...{
            on: {
              'update:dialogVisible': this.setDialogVisible,
            },
          }}
        />
      </div>
    )
  }

  setDialogVisible(val: boolean) {
    this.applyInvoiceDialogVisible = val
  }

  created() {}

  mounted() {
    // 获取路由交易状态
    this.type =
      (
        this.typeList.find(item => item.id === this.$route.params.type) || {
          id: '',
        }
      ).id || this.typeList[0].id
    this.orderNo = this.$route.query.orderNo || ''
    if (!!this.orderNo) {
      this.$router.replace({ name: 'myOrderList', params: { type: this.type } })
    }
    this.query()
  }

  get statusArry() {
    return [{ key: 0, text: '全部' }].concat(
      statusList.filter((item: any) => item.key !== 6)
    )
  }

  get getOperations() {
    const btns: any[] = [
      {
        id: 0,
        text: '查看申请单',
        onClick: (index: number, rows: any) => {
          // this.detail(rows);
          if (!rows.sealApplyId) {
            this.$message.error('无效申请单')

            return
          }
          this.$router.push({
            name: 'newApply',
            query: { id: rows.sealApplyRecordNo },
          })
        },
      },
      {
        id: 1,
        text: '查看物流',
        isPopover: true,
        onClick: (index: number, rows: any) => {
          // this.takeOver(rows);
        },
        onHover: (index: number, rows: any) => {
          // if (rows.sealUseType === 1) {
          this.queryByOrderInfo(rows)
          // }
        },
        popoverContent: this.popoverRender,
      },
      {
        id: 2,
        text: '前往支付',
        onClick: (index: number, rows: any) => {
          // this.detail(rows);
          this.$router.push({
            name: 'orderConfirm',
            query: { orderId: rows.payOrderId, sealApplyId: rows.sealApplyId },
          })
        },
      },
      {
        id: 3,
        text: '申请开票',
        disabled: this.invoiceDisabled,
        onClick: (index: number, rows: any) => {
          this.invoiceDisabled = true
          this.invoiceDirect(rows.payOrderId)
            .then((res: any) => {
              this.query()
              this.applyInvoicePayOrderId = rows.payOrderId
              this.applyInvoiceDialogVisible = true
            })
            .finally(() => {
              this.invoiceDisabled = false
            })
        },
      },
      {
        id: 4,
        text: '下载发票',
        onClick: (index: number, rows: any) => {
          // this.invoiceDownLoad(rows.payOrderId)
          this.download(rows)
        },
      },
      {
        id: 5,
        text: '申请开票',
        onClick: (index: number, rows: any) => {
          this.applyInvoiceHandler(rows)
        },
      },
      {
        id: 6,
        text: '开票详情',
        onClick: (index: number, rows: any) => {
          this.applyInvoiceHandler(rows)
        },
      },
      {
        id: 7,
        text: '取消订单',
        isDelete: true,
        onClick: (index: number, rows: any) => {
          this.closeOrder(rows)
        },
      },
      {
        id: 8,
        text: '查看退款详情',
        onClick: (index: number, rows: any) => {
          this.showRefundDialog(rows)
        },
      },
      {
        id: 9,
        text: '确认收货',
        onClick: (index: number, rows: any) => {
          this.takeOver(rows)
        },
      },
    ]

    return btns
  }

  showRefundDialog(row: any) {
    this.setStateData({
      refundDialogVisible: true,
      refundData: row,
    })
  }

  toNewApply() {
    this.$router.push({ name: 'applyPage', params: { type: 'newApply' } })
  }

  get getTypeList() {
    return [
      this.typeList[0],
      this.typeList[1],
      this.typeList[2],
      this.typeList[3],
      this.typeList[5],
    ]
  }

  queryByOrderInfo(rows: any) {
    this.queryByOrderId(rows.payOrderId).then((res: any) => {
      const sealList = this.orderList.map((seal: any) => {
        let info: any = {}
        if (seal.sealApplyId === rows.sealApplyId) {
          info = res
        }
        Object.keys(info).forEach(
          (key: any) => info[key] === null && delete info[key]
        ) // 去除null

        return {
          ...seal,
          ...info,
        }
      })
      this.orderList = sealList
    })
  }

  download(row: any) {
    this.applyInvoicePayOrderId = row.payOrderId
    this.applyInvoiceDialogVisible = true
  }

  popoverRender(row: any) {
    return (
      <div class={operationStyles.popoverContent}>
        <p
          class={{
            [operationStyles.title]: true,
            [operationStyles.longTitle]:
              row.payType === 1 &&
              row.sealUseType === 1 &&
              !!row.expressPayType &&
              row.expressPayType !== 0,
          }}
          style={{ color: statusColor[row.status] }}
        >
          <i class="el-icon-warning" />
          {orderStatusList[row.status]}
        </p>
        {row.payType === 2 && row.sealUseType === 1 && (
          <p class={operationStyles.tips}>
            {
              '采用统一付费方式的UKey将会直接投递至统一付费方负责人地址请主动联络负责人领取'
            }
          </p>
        )}
        {row.sealUseType === 2 && (
          <p class={operationStyles.tips}>
            {row.status === 2
              ? '云签章支付成功后需要后台审核人员确认发货后才可正常使用。'
              : row.status === 3
              ? '云签章已可以正常使用，请确认收货完成交易'
              : row.status === 4
              ? '云签章已可以正常使用'
              : ''}
          </p>
        )}
        {row.status === 2 && row.payType === 1 && row.sealUseType === 1 && (
          <p class={operationStyles.tips}>
            如需修改收货地址请联络服务热线：4000878198转3(政务服务专线)
          </p>
        )}
        <p />
        {
          <div class={operationStyles.logistics}>
            {row.payType === 1 &&
              row.sealUseType === 1 &&
              !!row.expressPayType &&
              row.expressPayType !== 0 && (
                <div class={operationStyles.part}>
                  <p
                    class={{
                      [operationStyles.title]: true,
                      [operationStyles.longTitle]:
                        row.payType === 1 &&
                        row.sealUseType === 1 &&
                        !!row.expressPayType &&
                        row.expressPayType !== 0,
                    }}
                  >
                    快递支付方式：
                  </p>
                  <p class={operationStyles.content}>
                    {formatStatus(expressPayTypes, row.expressPayType)}
                  </p>
                </div>
              )}
            {row.logisticsNumber && (
              <div class={operationStyles.part}>
                <p
                  class={{
                    [operationStyles.title]: true,
                    [operationStyles.longTitle]:
                      row.payType === 1 &&
                      row.sealUseType === 1 &&
                      !!row.expressPayType &&
                      row.expressPayType !== 0,
                  }}
                >
                  {row.logisticsCompany}：
                </p>
                <p class={operationStyles.content}>{row.logisticsNumber}</p>
              </div>
            )}
            {row.deliveryTime && (
              <div class={operationStyles.part}>
                <p
                  class={{
                    [operationStyles.title]: true,
                    [operationStyles.longTitle]:
                      row.payType === 1 &&
                      row.sealUseType === 1 &&
                      !!row.expressPayType &&
                      row.expressPayType !== 0,
                  }}
                >
                  发货时间：
                </p>
                <p class={operationStyles.content}>{row.deliveryTime}</p>
              </div>
            )}
            {row.confirmReceivingTime && (
              <div class={operationStyles.part}>
                <p
                  class={{
                    [operationStyles.title]: true,
                    [operationStyles.longTitle]:
                      row.payType === 1 &&
                      row.sealUseType === 1 &&
                      !!row.expressPayType &&
                      row.expressPayType !== 0,
                  }}
                >
                  收货时间：
                </p>
                <p class={operationStyles.content}>
                  {row.confirmReceivingTime}
                </p>
              </div>
            )}
          </div>
        }
        {row.sealUseType === 1 && !!row.deliveryName && (
          <div class={operationStyles.delivery}>
            {!!row.deliveryName && (
              <div class={operationStyles.part}>
                <p
                  class={{
                    [operationStyles.title]: true,
                    [operationStyles.longTitle]:
                      row.payType === 1 &&
                      row.sealUseType === 1 &&
                      !!row.expressPayType &&
                      row.expressPayType !== 0,
                  }}
                >
                  收货人：
                </p>
                <p class={operationStyles.content}>{row.deliveryName}</p>
              </div>
            )}
            {!!row.deliveryMobile && (
              <div class={operationStyles.part}>
                <p
                  class={{
                    [operationStyles.title]: true,
                    [operationStyles.longTitle]:
                      row.payType === 1 &&
                      row.sealUseType === 1 &&
                      !!row.expressPayType &&
                      row.expressPayType !== 0,
                  }}
                >
                  联系方式：
                </p>
                <p class={operationStyles.content}>
                  {desensitization(row.deliveryMobile)}
                </p>
              </div>
            )}
            {!!row.postCode && (
              <div class={operationStyles.part}>
                <p
                  class={{
                    [operationStyles.title]: true,
                    [operationStyles.longTitle]:
                      row.payType === 1 &&
                      row.sealUseType === 1 &&
                      !!row.expressPayType &&
                      row.expressPayType !== 0,
                  }}
                >
                  邮编：
                </p>
                <p class={operationStyles.content}>{row.postCode}</p>
              </div>
            )}
            {row.fixedTelephone && (
              <div class={operationStyles.part}>
                <p
                  class={{
                    [operationStyles.title]: true,
                    [operationStyles.longTitle]:
                      row.payType === 1 &&
                      row.sealUseType === 1 &&
                      !!row.expressPayType &&
                      row.expressPayType !== 0,
                  }}
                >
                  固定电话：
                </p>
                <p class={operationStyles.content}>{row.fixedTelephone}</p>
              </div>
            )}
            {(!!row.consigneeArea ||
              !!row.deliveryAddress ||
              !!row.consigneeArea) && (
              <div class={operationStyles.part}>
                <p
                  class={{
                    [operationStyles.title]: true,
                    [operationStyles.longTitle]:
                      row.payType === 1 &&
                      row.sealUseType === 1 &&
                      !!row.expressPayType &&
                      row.expressPayType !== 0,
                  }}
                >
                  收货地址：
                </p>
                <p
                  class={operationStyles.content}
                  title={
                    (row.consigneeArea || '') + (row.deliveryAddress || '')
                  }
                >
                  {(row.consigneeArea || '') + (row.deliveryAddress || '')}
                </p>
              </div>
            )}
          </div>
        )}
      </div>
    )
  }

  filterOpera(row: any) {
    const { status } = row
    const { invoiceStatus } = row
    const { payType } = row
    const detailOp: any[] = row.sealApplyId ? [this.getOperations[0]] : [] // 判断如果不存在申请id
    if ((row.orderNo || '').indexOf('O') !== (row.orderNo || '').length - 1) {
      // 新版订单不是以字母O结尾
      if (status === 1 || status === 5) {
        return detailOp.concat([this.getOperations[2], this.getOperations[7]])
      } else if (status === 6) {
        // 待统付方审核
        return detailOp
      } else if (status === 2 || status === 3) {
        return detailOp
          .concat([this.getOperations[1]])
          .concat(
            payType === 1
              ? [
                  invoiceStatus === 2
                    ? this.getOperations[4]
                    : this.getOperations[3],
                ]
              : []
          )
          .concat(status === 3 ? this.getOperations[9] : [])
      } else if (status === 4) {
        return detailOp
          .concat([this.getOperations[1]])
          .concat(
            payType === 1
              ? [
                  invoiceStatus === 2
                    ? this.getOperations[4]
                    : this.getOperations[3],
                ]
              : []
          )
      } else if (
        status === 90 ||
        status === 91 ||
        status === 92 ||
        status === 93 ||
        status === 94 ||
        status === 95
      ) {
        console.log('退款管理')

        return detailOp.concat([this.getOperations[8]])
      }

      return detailOp
    }
    // 老的订单
    if (status === 4 && payType === 1) {
      // 订单交易完成且自付费
      if (invoiceStatus === 1) {
        // 未开票
        return detailOp.concat([this.getOperations[1], this.getOperations[5]])
      }

      return detailOp.concat([this.getOperations[1], this.getOperations[6]])
    }
    if (status === 2 || status === 3 || status === 4) {
      return detailOp.concat(
        [this.getOperations[1]].concat(
          status === 3 ? this.getOperations[9] : []
        )
      )
    }

    return detailOp
  }
  arraySpanMethod({ row, column, rowIndex, columnIndex }: any) {
    if (columnIndex === 1) {
      return [1, 9]
    } else if (columnIndex >= 2) {
      return [0, 0]
    }
  }

  queryStatusCount() {
    this.queryAllStatusCount().then((data: any) => {
      this.typeList = this.typeList.map((type: any) => {
        // const count: number = data[type.tag]
        return {
          ...type,
          total: data[type.tag],
        }
      })
    })
  }

  async query() {
    this.pageIndex = 1
    await this.queryList()
  }
  async queryList() {
    this.queryStatusCount()
    this.orderCloseTimer && clearInterval(this.orderCloseTimer)
    let createStartTime: any = ''
    let createEndTime: any = ''
    if (Array.isArray(this.daterange)) {
      ;[createStartTime, createEndTime] = this.daterange
      createStartTime = createStartTime.fullFormat()
      createEndTime = createEndTime.fullFormat()
    }
    //
    this.loading = true
    await this.$nextTick()
    //
    const payStatus = this.payStatus
      .concat(this.payStatus.indexOf(90) !== -1 ? [91, 92, 93, 95] : [])
      .concat(this.payStatus.indexOf(99) !== -1 ? [96, 97, 98] : [])
      .concat(this.payStatus.indexOf(1) !== -1 ? [5, 6] : []) // 订单关闭包含：超时取消与用户取消；待付款包含：待支付与支付中、待统付方审核
    await this.queryPayOrderList({
      createStartTime: createStartTime,
      createEndTime: createEndTime,
      orderStatus:
        this.type === 'all'
          ? payStatus
          : this.type === 'refund'
          ? this.payStatus.length > 0
            ? payStatus
            : typeList[this.type]
          : typeList[this.type], // 退款管理与所有订单是包含订单状态
      pageIndex: this.pageIndex,
      pageNumber: this.pageSize,
      orderNo: this.orderNo,
      applyOrganizeName: this.applyOrganizeName,
      payer: this.payer,
      payType: this.payType ? [this.payType] : [],
    })
      .then((res: any) => {
        this.$nextTick(() => {
          this.loading = false
        })
        this.orderList = res.list.map((item: any, index: number) => {
          let goods = (item.goods || []).map((good: any) => {
            const name =
              (amountList.find(amount => amount.key === good.goodsType) || {})
                .label || ''

            return {
              ...good,
              name,
            }
          })
          goods = goods.filter((good: any) => good.goodsType !== 3) || []

          // let orderCloseTime = null
          // orderCloseTime = item.orderCloseTime
          return {
            ...item,
            // orderCloseTime,
            // closeTime,
            goods,
          }
        })
        this.setTimeDown(true)
        this.total = res.total
        const table = this.$refs.table as Table
        table.doLayout()
      })
      .catch((e: any) => {
        this.$nextTick(() => {
          this.loading = false
        })
      })
  }

  handleSizeChange(val: number) {
    this.pageIndex = 1
    this.pageSize = val
    this.queryList()
  }

  handleCurrentChange(val: number) {
    this.pageIndex = val
    this.queryList()
  }

  reset() {
    this.payStatus = []
    this.daterange = ''
    this.orderNo = ''
    this.applyOrganizeName = ''
    this.payer = ''
    this.payType = ''
    this.query()
  }

  typeChange(id: string, key: number) {
    if (id !== this.type) {
      this.type = id
      this.$router.replace({ params: { type: id } })
      this.payStatus = []
      this.orderNo = ''
      this.daterange = ''
      this.total = 0
      this.orderList = []
      this.applyOrganizeName = ''
      this.payer = ''
      this.payType = ''
      this.query()
    }
  }

  takeOver(row: any) {
    this.receiptConfirm(row.sealApplyId).then(async (res: any) => {
      this.$message.success('已确认收货')
      await this.query()
      this.queryByOrderInfo(row)
    })
  }

  countDownTime(time: number, step?: any, cb?: any) {
    let times = time
    if (step) step(times)
    this.orderCloseTimer && clearInterval(this.orderCloseTimer)
    this.orderCloseTimer = setInterval(() => {
      if (times <= 0) {
        this.orderCloseTimer && clearInterval(this.orderCloseTimer)
        if (cb) cb()

        return
      }

      times--
      if (step) step(times)
    }, 1000)
  }

  setTimeDown(flag?: boolean) {
    let time = 0
    this.orderList = this.orderList.map((item: any) => {
      const closeTime = (item.orderCloseTime || '').replace(
        new RegExp(/-/gm),
        '/'
      ) // 使用/替换-兼容其他浏览器
      let theTime = item.orderCloseTime
        ? new Date(closeTime).getTime() - new Date().getTime()
        : 0
      theTime = theTime > 0 ? theTime : 0

      if (time === 0 || (theTime > 0 && theTime < time)) {
        time = theTime
      }

      return {
        ...item,
        theTime: theTime,
        closeTime: formatTime(theTime),
      }
    })

    if (time > 0 && flag) {
      this.countDownTime(
        Math.round(time / 1000),
        (times: number) => {
          // a=times
          console.log(times)
          this.setTimeDown()
        },
        () => {
          this.queryList()
        }
      )
    }
  }

  closeOrder(row: any) {
    // 关闭订单（仅支持统一付费）
    //
    this.cancelPayOrder(row.payOrderId).then((res: any) => {
      this.$message.success('取消订单成功')
      this.query()
    })
  }

  applyInvoiceHandler(row: any) {
    payOrder.queryPayOrderInfo(row.payOrderId).then((res: any) => {
      console.log(res, 'res')
      res.data.payOrderId = row.payOrderId
      this.setStateData({
        applyInvoiceVisible: true,
        applyInvoiceData: {
          ...res.data,
          invoiceStatus: row.invoiceStatus,
          // invoiceStatus: 2
        },
      })
    })
  }

  beforeDestroy() {
    this.orderCloseTimer && clearInterval(this.orderCloseTimer)
  }
}
